<?php

namespace nimo\common\io;

use \SplFileObject;
/*
 * new FilteredFile($f, function($value) use($toCharset, $fromCharset){ return mb_convert_encoding($value, $toCharset, $fromCharset); });
 */
class FilteredFile extends SplFileObject {
    protected $filter_func = null;
    public function __construct($filename, $filter_func = null) {
        if (is_callable($filter_func)) {
            $this->filter_func = $filter_func;
        }
        return parent::__construct($filename);
    }
    public function current() {
        $value = parent::current();
        if (is_callable($this->filter_func)) {
            $filter_func = $this->filter_func;
            if ($this->getFlags() & self::READ_CSV) {
                $temp = array();
                foreach ( $value as $element ) {
                    $temp[] = $filter_func($element);
                }
                $value = $temp;
            } else {
                $value = $filter_func($value);
            }
        }
        return $value;
    }
    public static function convertedCSV($filename, array $configs = array()) {
        $locale = isset($configs['locale']) ? $configs['locale'] : 'ja_JP.UTF-8';
        $toCharset = isset($configs['toCharset']) ? $configs['toCharset'] : 'utf-8';
        // MS932, Shift_JIS
        $fromCharset = isset($configs['fromCharset']) ? $configs['fromCharset'] : 'utf-8';
        $delimiter = isset($configs['delimiter']) ? $configs['delimiter'] : ',';
        $enclosure = isset($configs['enclosure']) ? $configs['enclosure'] : '"';
        $escape = isset($configs['escape']) ? $configs['escape'] : '\\';

        $org_locale = setlocale(LC_ALL, $locale);
        $data = file_get_contents($filename);
        $data = mb_convert_encoding($data, $toCharset, $fromCharset);
        $temp = tmpfile();
        $meta = stream_get_meta_data($temp);
        fwrite($temp, $data);
        setlocale(LC_ALL, $org_locale);

        $file = new SplFileObject($meta['uri']);
        $file->setFlags(SplFileObject::READ_CSV);
        $file->setCsvControl($delimiter, $enclosure, $escape);

        $csv = array();
        foreach ( $file as $line ) {
            $csv[] = $line;
        }
        unset($file);
        fclose($temp);
        unset($temp);
        return $csv;
    }
}
